<template>
  <el-dialog :title="title" :visible="showAddDialog" @close="cancelBtn">
    <el-form ref="addForm" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name" label-width="120px">
        <el-input
          v-model.trim="form.name"
          autocomplete="off"
          placeholder="1-50字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code" label-width="120px">
        <el-input
          v-model.trim="form.code"
          autocomplete="off"
          placeholder="1-50字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager" label-width="120px">
        <el-select
          v-model="form.manager"
          placeholder="请选择"
          @focus="getEmpList"
        >
          <el-option
            v-for="item in empList"
            :label="item.username"
            :value="item.username"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce" label-width="120px">
        <el-input
          type="textarea"
          :row="4"
          v-model="form.introduce"
          placeholder="1-300字符"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelBtn">取 消</el-button>
      <el-button type="primary" @click="addDept">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getDepartments,
  addDepartment,
  getDeptDetail,
  editDept,
} from "@/api/departments";
import { getEmpSimpleList } from "@/api/employees";
export default {
  name: "add-dept",
  props: {
    showAddDialog: {
      type: Boolean,
      default: false,
    },
    pid: {
      type: String,
      required: true,
    },
    code: {
      type: String,
      default: "",
    },
  },
  data() {
    let checkName = async (rule, value, callback) => {
      // 获得部门列表
      let res = await getDepartments();

      let repeat = false;
      // 编辑部门
      if (this.form.id) {
        // 过滤出列表中为选中节点的同级节点
        let list = res.data.depts.filter((item) => item.pid == this.form.pid);

        // 遍历同级节点是否有相同的部门名称并且要排除自己
        repeat = list.some(
          (item) => item.name == value && value != this.oldForm.name
        );
      } else {
        // 过滤出列表中为选中节点的子节点
        let list = res.data.depts.filter((item) => item.pid == this.pid);

        // 遍历选中节点的子节点进行判断有是否与用户输入的部门名称相同,之所以不用forEach是因为在forEach中return不能中断遍历
        repeat = list.some((item) => item.name == value);
      }
      repeat
        ? callback(new Error("不能存在相同的部门名称，请修改！"))
        : callback();
    };
    let checkCode = async (rule, value, callback) => {
      // 获得部门列表
      let res = await getDepartments();

      let repeat = false;
      let list = res.data.depts;
      if (this.form.id) {
        // 遍历除了本节点之外的所有节点是否有项目的部门编号
        repeat = list.some(
          (item) =>
            item.code == value && item.code != this.oldForm.code && value
        );
      } else {
        // 遍历所有节点是否存在相同的部门编号
        repeat = list.some((item) => item.code == value && value);
      }

      repeat
        ? callback(new Error("组织架构中已存在部门使用该编码，请修改！"))
        : callback();
    };
    return {
      // 部门负责人列表
      empList: [],
      // 旧表单的名字和编号
      oldForm: {
        name: "",
        code: "",
      },
      form: {
        name: "",
        code: "",
        manager: "",
        introduce: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "内容在1-50字符",
            trigger: "blur",
          },
          {
            validator: checkName,
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
          {
            min: 1,
            max: 50,
            message: "内容在1-50字符",
            trigger: "blur",
          },
          {
            validator: checkCode,
            trigger: "blur",
          },
        ],
        manager: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        introduce: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
          {
            min: 1,
            max: 300,
            message: "内容在1-300字符",
            trigger: "blur",
          },
        ],
      },
    };
  },

  methods: {
    async getEmpList() {
      let res = await getEmpSimpleList();
      this.empList = res.data;
    },
    async getDeptDetail(id) {
      let res = await getDeptDetail(id);
      this.oldForm.name = res.data.name;
      this.oldForm.code = res.data.code;
      this.form = res.data;
    },
    addDept() {
      this.$refs.addForm.validate(async (v) => {
        if (v) {
          // 编辑部门
          if (this.form.id) {
             await editDept(this.form);
            this.$message.success("修改部门信息成功！");
          } else {
            await addDepartment({
              ...this.form,
              pid: this.pid,
            });
            this.$message.success("新增部门成功！");
          }
          // 告诉父组件重新获取输出
          this.$emit("addDepts");
          // 关闭对话框
          this.$emit("update:showAddDialog", false);
        }
      });
    },
    cancelBtn() {
      // 因为resetFields只能重置表单上的数据，非表单上的数据并不会重置，所以我们的id并不会重置，导致无法区分新增还是编辑
      (this.form = {
        name: "",
        code: "",
        manager: "",
        introduce: "",
      }),
        // 重新校验字段
        this.$refs.addForm.resetFields();
      // 关闭
      this.$emit("update:showAddDialog", false);
    },
  },
  computed: {
    title() {
      return this.form.id ? "编辑部门" : "新增部门";
    },
  },
};
</script>

<style></style>
